from datetime import datetime
from enum import Enum
from typing import List, Optional

from pydantic import BaseModel, Field, model_validator


class CertificateStatus(str, Enum):
    pending_validation = "pending_validation"
    issued = "issued"
    deployed = "deployed"
    revoked = "revoked"


class CertificateBase(BaseModel):
    provider: Optional[str] = Field(default=None, description="云厂商 (可选)")
    credential_id: Optional[str] = Field(default=None, description="凭据ID (自动申请时必填)")
    common_name: str = Field(..., description="主域名")
    domains: List[str] = Field(default_factory=list, description="域名列表")


class CertificateCreate(CertificateBase):
    auto_renew: bool = True


class Certificate(BaseModel):
    id: str
    provider: Optional[str] = None
    credential_id: Optional[str] = None
    common_name: str
    domains: List[str]
    status: CertificateStatus
    auto_renew: bool
    order_url: Optional[str] = None
    created_at: datetime
    updated_at: datetime
    expires_at: Optional[datetime] = None


class CertificateIdRequest(BaseModel):
    id: str


class CertificateAutoApplyRequest(BaseModel):
    credential_id: str
    domains: List[str]


class CertificateManualApplyRequest(BaseModel):
    domains: List[str]


class CertificateOrderCreateRequest(BaseModel):
    domains: List[str] = Field(..., description="域名列表")


class CertificateChallenge(BaseModel):
    domain: str
    token: str
    validation_url: str
    key_authorization: str
    txt_record_name: str
    txt_record_value: str
    authorization_url: Optional[str] = None


class CertificateOrderResponse(BaseModel):
    order_id: str
    status: str
    message: str
    challenges: Optional[List[CertificateChallenge]] = None


class CertificateRenewRequest(BaseModel):
    id: str


class CertificateUploadRequest(BaseModel):
    provider: Optional[str] = None
    common_name: str
    certificate_pem: str
    private_key_pem: str


class CertificateManualApplyResponse(BaseModel):
    order_url: str
    challenges: List[CertificateChallenge]


class CertificateVerifyRequest(BaseModel):
    order_id: Optional[str] = None
    order_url: Optional[str] = None

    @model_validator(mode='after')
    def check_one_of(self):
        if not self.order_id and not self.order_url:
            raise ValueError("Either order_id or order_url must be provided")
        return self
